package com.retallife.user.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.retallife.user.exception.Result;
import com.retallife.user.pojo.User.*;
import com.retallife.user.service.Admin.AdminService;
import com.retallife.user.service.User.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
@Api(tags = "用户信息类")
@RequestMapping(method = {RequestMethod.POST,RequestMethod.GET})
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    AdminService adminService;

    //Email所需要的类
    @Autowired
    JavaMailSenderImpl mailSender;

    //验证码所需要的配置文件
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "查询User表中的所有信息")
    @RequestMapping("findAllUser")
    public List<UserVo> findAllUser() {
        return userService.findAllUser();
    }

    @ApiOperation(value = "查询User表中的某个用户的信息")
    @RequestMapping("findUser")
    public List<UserUpdateVo> findUser(UserNameVo userNameVo) {
        return userService.findUser(userNameVo);
    }

    @ApiOperation(value = "验证码")//用了Swagger，要是没有就注释即可
    @RequestMapping(value = "defaultKaptcha", produces = "image/jpg")//produces = "image/jpg"让Swagger2能显现image图片
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            //Key-value的形式，key：vrifyCode  value：createText
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //输出保存到session中的验证码
            System.out.println("createText:" + createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    @ApiOperation(value = "查询用户的账号密码是否存在")
    @RequestMapping("findLoginUser")
    public Result findLoginUser(@RequestBody UserLoginVo userLoginVo, HttpServletRequest httpServletRequest, HttpSession session) {
        //得到session里面的，key为“vrifyCode”的value值
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        if (!captchaId.equals(userLoginVo.getCode())) {
            return Result.ok("登陆失败");
        } else {
            //判断账号和密码是否一致
            int result = userService.findLoginUser(userLoginVo);
            if (result > 0) {
                //建立用户名的缓存
                String userName = userLoginVo.getUserName();
                session.setAttribute("userName",userName);
                return Result.ok("登陆成功");
            }
        }
        return Result.ok("登陆失败");
    }

    @ApiOperation(value = "查询用户的忘记的密码，经邮件发送密码回来")
    @RequestMapping("findPasswordUser")
    public Result findPasswordUser(@RequestBody UserFindPasswordVo userFindPasswordVo) {
        String password = userService.findPasswordUser(userFindPasswordVo);
        if (password != null) {
            //一个简单的邮件
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            //标题
            mailMessage.setSubject("欢迎");
            //内容
            mailMessage.setText("您的密码为：" + password + "。为了您的信息安全，请不要将您的密码告诉其他人");
            //发给谁？
            mailMessage.setTo(userFindPasswordVo.getUserEmail());
            //谁发送？
            mailMessage.setFrom("wsw1335860166@163.com");
            //信息模板
            mailSender.send(mailMessage);
            return Result.ok("查询密码成功");
        }
        return Result.ok("查询密码失败");
    }

    @ApiOperation(value = "增加用户的账号密码,注册成功会有邮件提示")
    @RequestMapping("addLoginUser")
    public Result addLoginUser(@RequestBody UserRegistVo userRegistVo) {
        //判断用户是否重名
        UserNameVo userNameVo  = new UserNameVo();
        String userName1 = userRegistVo.getUserName();
        userNameVo.setUserName(userName1);
        List<UserVo> userNameVos = adminService.AdminFoundUser(userNameVo);

        if (userNameVos.size()==0) {
            //增加注册用户
            int result = userService.addRegistUser(userRegistVo);
            if (result > 0) {
                //为创建的用户添加默认图片和默认的特征码(进行修改，将空的userHeadImage改成有自定义网址)
                UserHeadImageVo userHeadImageVo = new UserHeadImageVo();

                String headImage = "https://img-blog.csdnimg.cn/20210303194624899.png";
                userHeadImageVo.setUserHeadImage(headImage);
                String state = "0";
                int fraction = 0;
                userHeadImageVo.setUserState(state);
                userHeadImageVo.setUserFraction(fraction);
                String userName = userRegistVo.getUserName();
                userHeadImageVo.setUserName(userName);

                userService.addHeadImageUser(userHeadImageVo);

                //一个简单的邮件
                SimpleMailMessage mailMessage = new SimpleMailMessage();
                //标题
                mailMessage.setSubject("欢迎");
                //内容
                mailMessage.setText("欢迎您来到软特福，希望您购物愉快");
                //发给谁？
                mailMessage.setTo(userRegistVo.getUserEmail());
                //谁发送？
                mailMessage.setFrom("wsw1335860166@163.com");
                //信息模板
                mailSender.send(mailMessage);

                return Result.ok("增加成功");
            }
        }
        return Result.ok("增加失败，用户名重复");
    }

    @ApiOperation(value = "修改用户的基本信息(名字没修改)")
    @RequestMapping("updateUser")
    public Result updateUser(@RequestBody UserUpdateVo userUpdateVo){
        int result = userService.updateUser(userUpdateVo);
        if (result > 0){
            return Result.ok("修改成功");
        }
        return Result.ok("修改失败");
    }

    @ApiOperation(value = "修改用户的基本信息(名字修改了)")
    @RequestMapping("updateNameUser")
    public Result updateNameUser(@RequestBody UserUpdateVo userUpdateVo) {
        //判断用户是否重名
        UserNameVo userNameVo  = new UserNameVo();
        String userName1 = userUpdateVo.getUserName();
        userNameVo.setUserName(userName1);
        List<UserVo> userNameVos = adminService.AdminFoundUser(userNameVo);

        if (userNameVos.size()==0) {
            int result = userService.updateUser(userUpdateVo);
            if (result > 0) {
                return Result.ok("修改成功");
            }
        }
        return Result.ok("修改失败,用户名重名了");
    }
}
